public class LeetCode34 {
    public int[] searchRange(int[] nums, int target) {
        int[] ret = new int[]{-1, -1};
        int n = nums.length;
        int left = 0;
        int right = n - 1;
        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid;
                right = mid;
                break;
            }
        }
        if (n == 1 && nums[0] == target) {
            ret[1] = ret[0];
        }
        if (n == 0) {
            return ret;
        }
        while (left >= 0 && left < n && nums[left] == target) {
            ret[0] = left--;
        }
        while (right < n && right >= 0 && nums[right] == target) {
            ret[1] = right++;
        }
        return ret;
    }

    public int[] searchRange2(int[] nums, int target) {
        int[] ret = new int[]{-1, -1};
        int n = nums.length;
        if (n == 0 || n == 1 && nums[0] != target) {
            return ret;
        }
        int left = 0;
        int right = n - 1;
        for ( ; left < right; ) {//求左端点
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }//循环结束后left==right
        ret[0] = nums[right] == target ? right : -1;
        left = 0;
        right = n - 1;
        for ( ; left < right; ) {//求右端点
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }//循环结束后left==right
        ret[1] = nums[left] == target ? left : -1;
        return ret;
    }
}
